package com.yf.service;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
import com.yf.service.BindService.MyBinder;

public class MainActivity extends Activity {
	private ServiceConnection conn;
	private MyBinder binder;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		Intent service = new Intent(this, BindService.class);
		conn = new MyServiceConnection();
		// 参数一：intent
		// 参数二：ServiceConnection对象，可以接收服务开启或停止的消息
		// 参数三：开启服务时操作的选项
		bindService(service, conn, BIND_AUTO_CREATE);
	}

	public void start(View v) {
		Intent service = new Intent(this, MyService.class);
		startService(service);
	}

	public void stop(View v) {
		Intent name = new Intent(this, MyService.class);
		stopService(name);
	}

	public void bind(View v) {
		Intent service = new Intent(this, BindService.class);
		conn = new MyServiceConnection();
		// 参数一：intent
		// 参数二：ServiceConnection对象，可以接收服务开启或停止的消息
		// 参数三：开启服务时操作的选项
		bindService(service, conn, BIND_AUTO_CREATE);
	}

	public void callServiceMethod(View v) {
		binder.showToast("call BindService method");
	}

	private class MyServiceConnection implements ServiceConnection {

		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			// service就是从onBind方法返回的MyBinder实例对象
			Log.v("BindService", "onServiceConnected");
			binder = (MyBinder) service;
		}

		@Override
		public void onServiceDisconnected(ComponentName name) {
			Log.v("BindService", "onServiceDisconnected");
		}

	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		// 使用bindService开启的服务要用unbindService停止
		// unbind只能执行一行，否则会抛异常
		unbindService(conn);
	}
}
